package com.wgf.config;

import com.wgf.service.ChatPersistenceAssistant;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LLMConfig {
    @Resource
    private RedisChatMemoryStore redisChatMemoryStore;//注入上面定义的 RedisChatMemoryStore 组件

    @Bean
    public ChatModel chatModel()
    {
        return OpenAiChatModel.builder()
                    .apiKey(System.getenv("aliQwen-api"))
                    .modelName("qwen-plus")
                    .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
    }

    @Bean
    public ChatPersistenceAssistant chatMemoryAssistant(ChatModel chatModel) {

        ChatMemoryProvider chatMemoryProvider = memoryId -> MessageWindowChatMemory.builder()//使用消息窗口记忆，最多保存 1000 条消息
                .id(memoryId)
                .maxMessages(1000)
                .chatMemoryStore(redisChatMemoryStore)//设置 chatMemoryStore(redisChatMemoryStore)，将 Redis 存储注入到记忆系统中
                .build();

        return AiServices.builder(ChatPersistenceAssistant.class)//使用 AiServices 构建具有持久化记忆的聊天助手
                .chatModel(chatModel)//注入聊天模型
                .chatMemoryProvider(chatMemoryProvider)//注入记忆提供者
                .build();
    }

}